package com.yangrd.easypress.web;

import com.yangrd.easypress.model.Post;
import com.yangrd.easypress.repositoy.PostRepository;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author yangrd
 * @date 2019/4/2
 **/
@AllArgsConstructor

@Controller
public class PageController {

    private PostRepository repository;


    @GetMapping
    public String index(@PageableDefault(sort = "id",direction= Sort.Direction.DESC) Pageable pageable, Model model) {
        Page<Post> postPage = repository.findAll(pageable);
        model.addAttribute("page", postPage);
        return "www/index";
    }

    @GetMapping("/p/{id}")
    public String page(@PathVariable Long id, Model model) {
        Post post = repository.findById(id).orElseThrow(RuntimeException::new);
        model.addAttribute("post", post);
        return "www/page";
    }

    @GetMapping("admin")
    public String admin() {
        return "admin/post";
    }

    @GetMapping("admin/p/{id}")
    public String edit(@PathVariable Long id, Model model) {
        Post post = repository.findById(id).orElseThrow(RuntimeException::new);
        model.addAttribute("post", post);
        return "admin/edit";
    }

}
